import React, { useRef, useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Button, message, Space, Table, Input, Tag ,Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined ,EyeOutlined} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { apipage, apiDelete } from '@/services/system/apimanage';
import { useOutletContext } from '@umijs/max';
import AuthorizedButton from '@/components/AuthorizedButton';
interface ButtonData {
  id: string;
  pageId: string;
  resourceName: string;
  icon?: string;
  action: string;
}
const ApiManageList: React.FC = () => {
  const [records, setRecords] = useState<any[]>([]);
  const { buttonData } = useOutletContext<{ buttonData: ButtonData[] }>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const navigate = useNavigate();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async (params = {}) => {
    try {
      const response = await apipage({
        current: params?.current || 1,
        size: params?.pageSize || 10,
        ...params
      });
      if (response.code === 200) {
        setRecords(response.data.records);
        setPagination({
          current: response.data.current,
          pageSize: response.data.size,
          total: response.data.total,
        });
      }
    } catch (error) {
      console.error(error);
    }
  };

  const getScopeType = (type: string) => {
    const typeMap: Record<string, { text: string; color: string }> = {
      '1': { text: 'GET', color: 'green' },
      '2': { text: 'POST', color: 'blue' },

    };
    return typeMap[type] || { text: type, color: 'default' };
  };

  const getStatusText = (status: number) => {
    const statusMap: Record<number, { text: string; color: string }> = {
      0: { text: '正常', color: 'success' },
      1: { text: '禁用', color: 'error' },
    };
    return statusMap[status] || { text: '未知', color: 'default' };
  };

  const columns = [
    {
      title: '编号',
      dataIndex: 'id',
    },
    {
      title: '接口名称',
      dataIndex: 'scopeName',
    },
    {
      title: '接口类型',
      dataIndex: 'scopeType',
      render: (type: string) => {
        const { text, color } = getScopeType(type);
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '接口地址',
      dataIndex: 'scopePath',
    },
    {
      title: '权限标识',
      dataIndex: 'scopePermission',
    },
    {
      title: '排序',
      dataIndex: 'sort',
    },
    {
      title: '接口状态',
      dataIndex: 'status',
      render: (status: number) => {
        const { text, color } = getStatusText(status);
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <span>
        <Space split={<Divider type="vertical" />}>
          <AuthorizedButton
            buttonData={buttonData}
            action="edit"
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            编辑
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="delete"
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
              // backgroundColor:'red'
            }}
          >
            删除
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="view"
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            详情
          </AuthorizedButton>
        </Space>
      </span>
      ),
    },
  ];

  const handleAdd = () => {
    navigate('/system/apimanage/add');
  };

  const handleEdit = (record) => {
    navigate('/system/apimanage/edit', { state: { record } });
  };

  const handleDelete = async (record) => {
    try {
      const response = await apiDelete({ apiPermId: record.id });
      if (response.code === 200) {
        message.success('删除成功');
        fetchData();
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleView = (record) => {
    navigate('/system/apimanage/view', { state: { record } });
  };

  return (
    <PageContainer>
      <Space style={{ marginBottom: 16 }}>
      <AuthorizedButton
          buttonData={buttonData}
          action="add"
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          新增
        </AuthorizedButton>
      </Space>
      <Table
        columns={columns}
        dataSource={records}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, pageSize) => {
            fetchData({ current: page, size: pageSize });
          },
        }}
      />
    </PageContainer>
  );
};

export default ApiManageList;
